/**
 * Created by ROGSTAR on 2016/11/29.
 */
require.config(window.jshead);
require(['jquery', 'pages', "layer",'navigator','radialIndicator'], function ($, pg,layer) {
    layer.config({
        path: '/js/layer/'
    });

        radialIndicator.defaults.radius = 48;
        radialIndicator.defaults.barColor = "#fcb22f";
        radialIndicator.defaults.barBgColor = "#e8e8e8";
        radialIndicator.defaults.barWidth = 5;
        radialIndicator.defaults.percentage = true;
        radialIndicator.defaults.displayNumber = true;
        radialIndicator.defaults.fontSize = 26;
        radialIndicator.defaults.fontWeight = 'normal';
        $('#rate').radialIndicator();
        $('#rate').data('radialIndicator').value($('#rate').attr('data-value'));
    var itemId=decodeURI(window.location.href).split('?')[1];
    var itemCycleForCoupon=$('#itemCycleForCoupon').text();
    var amountC=0;
    var selectedId=null;
    var couponIcome1=0;
    var couponIcome2=0;
    var amountSelected=0;
    var couponId=null;
    //自动填入
    $('#autoValue').click(function () {

    	var insertvalue = "";
    	if(Number($('#accountMoney').text().replace(/,/g,""))<=Number($('#itemAccountLeft').text().replace(/,/g,"")))
    	{
    		insertvalue = Number($('#accountMoney').text().replace(/,/g,""))
    	}else if(Number($('#accountMoney').text().replace(/,/g,""))>Number($('#itemAccountLeft').text().replace(/,/g,""))){
    		insertvalue = Number($('#itemAccountLeft').text().replace(/,/g,""))
    	}
        $('#usableMoney').val(insertvalue);


    });
    //图片预览
    picTab($('#imgLarge'),$('.slider'),0);
    function picTab(ele,allNum,currentNum) {
        allNum.click(function () {
            currentNum = $(this).index($(".slider"));

            ele.show(300);
            var ImgSrc = $(this).attr('data-url');

            ele.css('background-image', 'url('+ImgSrc+')');
        });
        $('.close').click(function () {
            ele.hide(300);
            $('#payPassword_rsainput').val('');
            $(".guangbiao").css({"left":0});
            $(".sixDigitPassword").find("i").find("b").css({"display":"none"});
        });
        $('.left').click(function () {
            currentNum--;
            if (currentNum < 0) {
                currentNum = allNum.length - 1;
            }
            var ImgSrc = allNum.eq(currentNum).attr('data-url');
            ele.css('background-image', 'url('+ImgSrc+')');
        });

        $('.right').click(function () {
            currentNum++;
            if (currentNum > allNum.length - 1) {
                currentNum = 0;
            }
            var ImgSrc = allNum.eq(currentNum).attr('data-url');
            ele.css('background-image', 'url('+ImgSrc+')');
        })
    }
//tab切换
    $('#tabs div').click(function () {
        $(this).addClass('tab_active');
        var show=$('#contents .tab_content').eq($(this).index());
        show.show();
        $('#tabs div').not($(this)).removeClass('tab_active');
        $('#contents .tab_content').not(show).hide();
        if($(this).index()==2){
            //投标记录
            pg.paging(1, 8, "/debt/getDebtInvestList", 'recordList', 'recordListFunc', {id:itemId}, '', '');
        }
        if($(this).index()==1){
            //还款计划
            pg.paging(1, 8, "/debt/getDebtCollectList", 'debtList', 'debtListFunc', {id:itemId}, '#debtpages', '');
        }
    });
//收益计算器
    $('#cacuClose').click(function () {
        $('#cacuPanel').hide(300);
        $('#reset').click();
    });
    $('.caculator').click(function () {
        $('#cacuPanel').show(300);
        var investCycle=parseFloat($('#investCycle').text());
        var investRate=parseFloat($('#investRate').text());
        var repayMethod=$('#repayMethod').text();
        var leftItemAccount=$('#itemAccountLeft').text();
        if(leftItemAccount && leftItemAccount.indexOf(','!=0)){
            var left=parseFloat(leftItemAccount.replace(/,/g,''));
        }
        var investMoney=0;


        //校验计算器的
        $('#investMoneyCalcu').bind('keyup',function(){
            investMoney=$('#investMoneyCalcu').val();
            if(investMoney<=0){
                layer.tips('投资金额不能小于0',$('#investMoneyCalcu'));
                $('#investMoneyCalcu').val('')
            }else if(investMoney==''){
                layer.tips('请输入投资金额',$('#investMoneyCalcu'));
                $('#investMoneyCalcu').val('')
            }else if(investMoney>left){
                investMoney=parseFloat($('#investMoneyCalcu').val());
                layer.tips('投资金额不能不能大于项目余额',$('#investMoneyCalcu'));
            }
        })

        $('#cacu').click(function () {
            investMoney=$('#investMoneyCalcu').val();
                if(investMoney<=0){
                    layer.tips('投资金额不能小于0',$('#investMoneyCalcu'));
                }else if(investMoney==''){
                    layer.tips('请输入投资金额',$('#investMoneyCalcu'));
                }else if(investMoney >left){
                    investMoney=parseFloat($('#investMoneyCalcu').val());
                    layer.tips('投资金额不能不能大于项目余额',$('#investMoneyCalcu'));
                }else{
                    investMoney=parseFloat($('#investMoneyCalcu').val());
                    if(repayMethod=='一次性还款'){
                        console.log(investMoney)
                        var interest=(investMoney*investRate*investCycle/36000).toFixed(4);
                        var interest1 = interest.toString().substring(0, interest.toString().lastIndexOf('.')+3)
                        var principalInterest=(parseFloat(interest) + investMoney).toFixed(4);
                        var principalInterest1 = principalInterest.toString().substring(0, principalInterest.toString().lastIndexOf('.')+3)
                        $('#everyIntrerst_2').text(interest1);
                        $('#total_2').text(principalInterest1);
                    }
                    else if(repayMethod=='先息后本'){
                        var everyIntrerst=((investMoney * investRate*30)/36000).toFixed(4);
                        var everyIntrerst1 = everyIntrerst.toString().substring(0, everyIntrerst.toString().lastIndexOf('.')+3)
                        var total=(((investMoney * investRate*30)/36000)*investCycle/30+investMoney).toFixed(4);
                        var total1 = total.toString().substring(0, total.toString().lastIndexOf('.')+3)
                        $('#intrerst_1').text(everyIntrerst1);
                        $('#total_1').text(total1);
                    }
                    else if(repayMethod=='等额本息'){
                        var everyIntrerst1=(investMoney*investRate*investCycle/36000+investMoney*30/investCycle).toFixed(4);
                        var everyIntrerst2 = everyIntrerst1.toString().substring(0,everyIntrerst1.toString().lastIndexOf('.')+3)
                        var total1=(everyIntrerst1*(investCycle/30)+investMoney).toFixed(4);
                        var totla2 = total1.toString().substring(0,total1.toString().lastIndexOf('.')+3)
                        $('#intrerst_1').text(everyIntrerst2);
                        $('#total_1').text(totla2);
                    }
                }


        });
        $('#reset').click(function () {
            $('#investMoneyCalcu').val('');
            if(repayMethod=='一次性还款'){
                $('#intrerst_3').text('');
                $('#total_3').text('');
            }else if(repayMethod=='先息后本'){
                $('#everyIntrerst_2').text('');
                $('#lastIntrerst_2').text('');
                $('#total_2').text('');
            }else if(repayMethod=='等额本息'){
                $('#intrerst_1').text('');
                $('#total_1').text('');
            }

        })
    });
    //充值
    $('.close').click(function () {
        $('#needRecharge').hide(300);
    });
    $('#rechargeCancle').click(function () {
        $('#needRecharge').hide(300);
    });
//立即投资
    //判断输入框中的值
    $('#usableMoney').bind('keyup',function(){
        var itemAccountLeft=parseFloat($('#itemAccountLeft').text().replace(/,/g,''));
        var usableMoney=$('#usableMoney').val();
        if(usableMoney>itemAccountLeft){
            layer.tips('投资金额不能大于项目余额','#usableMoney');
            $('#usableMoney').val(itemAccountLeft)
            return
        }
    })

    $('#investNormal').click(function () {
        $.ajax({
            type: "POST",
            url: " /user/info/getInfo",
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.userRiskType == 0 || !data.userRiskType) {
                    layer.msg('您还未评估风险，即将为您前往风险评估');
                    var url=decodeURI(window.location.href);
                    $.cookie('the_cookie',url, {path: '/' });
                    setTimeout(function () {
                        window.location.href = "/user/assessment?" + data.id;
                    }, 1500);
                } else {
                    var accountMoney = parseFloat($('#accountMoney').text().replace(/,/g, ''));
                    var itemAccountLeft = parseFloat($('#itemAccountLeft').text().replace(/,/g, ''));
                    var minInvestMoney = parseFloat($('#minInvestMoney').text().replace(/,/g, ''));
                    var lock = $('#usableMoney').attr('data-value');
                    var usableMoney = $('#usableMoney').val();
                    if (usableMoney <= 0) {
                        layer.tips('投资金额不能小于0', '#usableMoney');
                        return
                    }
                    if (usableMoney == '') {
                        layer.tips('请输入投资金额', '#usableMoney');
                        return
                    }
                    if (usableMoney > itemAccountLeft) {
                        layer.tips('投资金额不能大于项目余额', '#usableMoney');
                        return
                    }
                    if (usableMoney > accountMoney) {
                        //账户余额不足
                        $('#needRecharge').show(300);
                        //充值
                        $('.close').click(function () {
                            $('#needRecharge').hide(300);
                        });
                        $('#rechargeCancle').click(function () {
                            $('#needRecharge').hide(300);
                        });

                    }
                    //定向密码校验
                    else if (lock == 'isLock') {
                        var password = $('#lockPsw').val();
                        if (password == '' || password == undefined) {
                            layer.tips('定向密码不能为空', '#lockPsw');
                            return
                        }
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                itemId: itemId,
                                password: password

                            },
                            url: "/invest/password",
                            success: function (data) {

                                if (data.result == 'success') {
                                    getPanel()
                                } else {
                                    layer.tips(data.messageText, '#lockPsw');
                                }


                            }
                        })

                    } else {
                        getPanel()
                    }
                    function getPanel() {
                        //弹出投资窗口,判断有无红包和加息券
                        $('#couponPanel').show(300);
                        $('#investAccountTotal').text(usableMoney + '元');
                        amountC = usableMoney;
                        getIncomeTiket(amountC);
                    }

                    //计算收益
                    function getIncomeTiket(amount) {
                        $.ajax({
                            type: "POST",
                            dataType: "JSON",
                            data: {
                                itemId: $("#itemId").val(),
                                deptId:itemId,
                                amount: amount
                            },
                            async: false,
                            url: "/invest/calculator",
                            success: function (data) {
                                $('#itemIncome').html(data.interest + '元');
                            }
                        })
                    }

                    $('.close').click(function () {
                        $('#couponPanel').hide(300)
                    })
                    $("#payPassword_rsainput").focus();
                }
            },
            error:function (data){
            }
        })
    });
    //立即投资
    $('#investFinal').click(function () {
        var payPassword=$("#payPassword_rsainput").val();
        var leftmoney = parseFloat($('#itemAccountLeft').text().replace(/,/g,""));
        if(amountC>leftmoney){
            layer.msg('投资金额超出可投金额');
            return
        }
        if($('#agreement').prop('checked')==false){
            layer.tips('是否同意借款协议','#agreement');
            return
        }
        if(payPassword.length<1){
            layer.msg('请输入交易密码');
            return
        }
        var layerLoad = layer.load(1);
        $.ajax({
            type: "POST",
            dataType: "json",
            data: {
                amount:amountC,
                debtId:itemId,
                payPassword:payPassword
                //couponId:couponId,
                //ticketId:selectedId
            },
            url: "/user/debt/buy",
            beforeSend: function () {
                // 禁用按钮防止重复提交
                $("#investFinal").attr({ disabled: "disabled" });
            },
            success: function (data) {
                layer.close(layerLoad);
                if(data.result=="fail"){
                    $("#investFinal").removeAttr("disabled");
                    if(data.messageText){
                        layer.msg(data.messageText);
                    }else{
                        layer.msg('系统异常');
                    }
                    setTimeout(function(){
                        $("#payPassword_rsainput").val('').focus();
                        $(".guangbiao").css({"left":0});
                        $(".sixDigitPassword").find("i").find("b").css({"display":"none"});
                    },1000)
                }else{
                    layer.msg('投资成功');
                    setTimeout(function(){
                        window.location.reload();
                    },2000)
                }
            },
            error:function(data) {

                layer.msg('通讯失败');
                setTimeout(function () {
                    $("#payPassword_rsainput").val('');
                    $(".guangbiao").css({"left": 0});
                    $(".sixDigitPassword").find("i").find("b").css({"display": "none"});
                }, 1000)
            }
            })
        });
    //计算年龄
    function   ages(str)
    {
        var   r   =   str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if(r==null)return   false;
        var   d=   new   Date(r[1],   r[3]-1,   r[4]);
        if   (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4])
        {
            var   Y   =   new   Date().getFullYear();
            $('#people_age').html(Y-r[1]+"岁");
        }
        $('#people_age').html("保密");
    }
    if($("#birthday").val()){
        ages($("#birthday").val());
    }else{
        $('#people_age').html("保密")
    }
    //支付弹框
    $("#payPassword_rsainput").bind("blur", function (){
        $(".sixDigitPassword span").removeClass("guangbiao");
    });
    $("#payPassword_rsainput").bind("focus", function (){
        $(".sixDigitPassword span").addClass("guangbiao");
        if($(".i-text").val().length==6){
            $(".guangbiao").css({"left":($(".i-text").val().length-1)*50});
        }else{
            $(".guangbiao").css({"left":($(".i-text").val().length)*50});
        }
    });
    $(".i-text").keyup(function()
    {
        var inp_v = $(this).val();
        var inp_l = inp_v.length;
        //$("p").html( "input的值为：" + inp_v +"; " + "值的长度为:" + inp_l);//测试用

        for( var x = 0; x<=6; x++)
        {
            //$("p").html( inp_l );//测试

            $(".sixDigitPassword").find("i").eq( inp_l ).prevAll("i").find("b").css({"display":"block"});
            $(".sixDigitPassword").find("i").eq( inp_l - 1 ).nextAll("i").find("b").css({"display":"none"});
            $(".guangbiao").css({"left":inp_l * 50});//光标位置
            if( inp_l == 0)
            {
                $(".sixDigitPassword").find("b").css({"display":"none"});
                $(".guangbiao").css({"left":0});
            }
            else if( inp_l == 6)
            {
                $(".sixDigitPassword").find("b").css({"display":"block"});
                $(".guangbiao").css({"left":5 * 50});
            }
        }
    });
    //支付页回车事件
    $(".bg_panel").keydown(function() {
        if (event.keyCode == "13") {//keyCode=13是回车键
            $('#investFinal').click();
        }
    });
});